
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from backend.models.models import User
from backend.auth import get_password_hash
from backend.database.session import SessionLocal
def add_user(username: str, password: str):
    """添加新用户"""
    db = SessionLocal()
    try:
        # 检查用户是否已存在
        existing_user = db.query(User).filter(User.username == username).first()
        if existing_user:
            print(f"用户 {username} 已存在")
            return False

        # 创建新用户
        hashed_password = get_password_hash(password)
        new_user = User(username=username, password_hash=hashed_password)
        db.add(new_user)
        db.commit()
        print(f"用户 {username} 添加成功")
        return True
    finally:
        db.close()


def update_user_password(username: str, new_password: str):
    """更新用户密码"""
    db = SessionLocal()
    try:
        user = db.query(User).filter(User.username == username).first()
        if not user:
            print(f"用户 {username} 不存在")
            return False

        user.password_hash = get_password_hash(new_password)
        db.commit()
        print(f"用户 {username} 密码更新成功")
        return True
    finally:
        db.close()


def list_users():
    """列出所有用户"""
    db = SessionLocal()
    try:
        users = db.query(User).all()
        if not users:
            print("没有用户")
            return []

        print("用户列表:")
        for user in users:
            print(f"ID: {user.id}, 用户名: {user.username}")
        return users
    finally:
        db.close()


if __name__ == "__main__":
    # 示例用法
    import sys

    if len(sys.argv) < 2:
        print("用法:")
        print("  python db_manager.py add <username> <password>  # 添加用户")
        print("  python db_manager.py update <username> <new_password>  # 更新用户密码")
        print("  python db_manager.py list  # 列出所有用户")
        sys.exit(1)

    command = sys.argv[1]

    if command == "add" and len(sys.argv) == 4:
        add_user(sys.argv[2], sys.argv[3])
    elif command == "update" and len(sys.argv) == 4:
        update_user_password(sys.argv[2], sys.argv[3])
    elif command == "list":
        list_users()
    else:
        print("无效的命令")
        
        
# 必须在D:\Git_Repository\NeuroVisionWeb\WebProject> 中以包形式运行(base) (.venv) PS D:\Git_Repository\NeuroVisionWeb\WebProject> python -m backend.db_manager add dockor 123